<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

$this->useClass("Action_Community_FeedHandler");
class Action_Community_ShowMember extends Action_Community_FeedHandler
{
	public function getFeedModel() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderItems");

		return new AggregatedModel_Feed_ReaderItems();
	}

	var $ajax_functions = array(
		'ajax_getSomePosts',
		'ajax_doSubmitMemberInfo'
		);

	public function ajax_getSomePosts( $page_number ) {

		$this->setParam("page_number", $page_number);

		$this->model->doStuff();

		$view = $this->rh->views->findByName('items:member');

		$view->data = $this->acl_assistant->template_data;
		$items = $this->model->getItems();
		foreach ($items as $i=>$item) {
			$items[ $i ]['type'] = $this->tdi_types[ $item['post']['tdi_oid'] ];
		}
		$view->data['items'] = $items;

		$items_node = &$this->rh->ctx->cp->add_node("items");
		$view->data['tag_sections']['single'] = count($this->getParam('tdis')) == 1 || isset($this->params['tdi_url']);

		$items_node->set_data( $view->getContent() ); // рендеринг итемов

		$this->addPagerNodes( &$this->rh->ctx->cp );
	}

	public function ajax_doSubmitMemberInfo ( $description ) {
		$cp = &$this->rh->ctx->cp;

		$description = trim($description);

		$user_id = $this->params['user_url'];
		if ($this->aa->acl_data['user_id'] == $user_id)   {
				$u['user']['oid']['=='] = $user_id;
				$user = $this->rh->ctx->store->find( $u )->next();
				$user->data['description'] = $description;
				$user->save();
				$user->inSense('user');
				$status = &$cp->add_node('status');
				$data = &$cp->add_node('data');
				$status->set_data(0);
				$data->set_data($description);
				$this->shutdown();
				return true;
		} else {
				$status = &$cp->add_node('status');
				$status->set_data(-1);
				$data = &$cp->add_node('data');
				$data->set_data('access denied');
				$this->shutdown();
				return false;
			}

		$this->shutdown();
	}

	protected function determineCustomModelParams() {
		// --- user --- {{{
		if (isset($this->params['user_url'])) {
			$user_url = $this->params['user_url'];
			$user = $this->rh->ctx->store->find( 'select objects where user.oid=:0', array($user_url))->next();
			$this->setParam('user', $user);
			$this->setParam('user_oid', $user->id);
		}
		// --- user --- }}}
	}

	protected function init() {

		// -- old theme HACK : 2008-05-21 : lucky -- {{{
		//$community_skin = 'platonica';
		//$tpl = $this->ctx->tpl;
		//$community_model = $this->ctx->mm->getModel("Community");
		//$community_model->setDefaultSkin($community_skin);
		//$tpl->setSkin($community_skin);
		//$views_php = $tpl->findFile('', 'views', $tpl->_skin, 'php');
		//unset ($config);
		//include $views_php; // got $config
		//$this->ctx->rh->views->setViewConfig($config);
		// -- old theme HACK : 2008-05-21 : lucky -- }}}

		parent::init();
		$this->m_tdi = $this->ctx->mm->getModel("Tdi", "m");
		$this->m_user = $this->ctx->mm->getModel('User', 'm');
		$tdi_oids = array();
		foreach ($this->aa->acl_data['tdi_list'] as $tdi) $tdi_oids[] = $tdi['id_object'];
		$this->tdi_types = $this->m_tdi->getSections($tdi_oids);
	}

	public function getWidgetsConfig ()
	{
		$widgets = array();

		$widgets[] = array (
			'name' => 'TagsWidget',
			'params' => array(
				'tag' => $this->getParam('tag'),
				'widget_position' => 'tags',
				'widget_view' => 'WG_TagsWidget',
				'user_oid'=>$this->aa->acl_data['user_id'],
			),
		);

		//$widgets[] = array (
		//	'name' => 'Feed_TdiMenuWidget',
		//	'params' => array(
		//		'community_oid' => $this->aa->acl_data['comity_oid'],
		//		'tdi_oid'=> $this->aa->acl_data['tdi_oid'],
		//		'widget_position' => 'tags',
		//		'widget_view' => 'WG_Feed_TdiMenuWidget',
		//	),
		//);

		//$widgets[] = array (
		//	'name' => 'RssWidget',
		//	'params' => array(
		//		'widget_view' => 'WG_RssWidget',
		//		'widget_position' => 'tags',
		//	),
		//);

		return $widgets;
	} // end of function getWidgetsConfig

	private function processItems($items) {
		foreach ($items as $i=>$item) {
			if ($item['post']['type'] == 'fvote') {
				// установить bool $item['voted'] если текущий пользователь голосовал
				$vm = $this->ctx->mm->getModel("Vote", "m");
				$aa = $this->aa;
				$items[$i]['already_voted'] = $vm->checkUserVote($item['post']['oid'], $aa->acl_data['user_id']);

				// создать ссылку на голосоватор за данный итем
				$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
				$ug->setRouter($this->rh->router);
				$ug->setParams(array(
					"community_url"=>$this->params['community_url'],
					"id_item"=>$item['post']['oid'],
					)
				);
				$items[$i]['vote_url'] = $ug->generateUrl();
				unset($ug);

				if ($item['post']['posted_by_id'] == $this->aa->acl_data['user_id']) {
					if ( $item['vote_closed'] ) {
						$items[$i]['can_open'] = 1;
					} else {
						$items[$i]['can_close'] = 1;
					}
				}

				$items[$i]['can_vote'] = (isset($this->aa->acl_data['user_id'])) ? true : false;
			}
			$items[$i]['type'] = $this->tdi_types[ $item['post']['tdi_oid'] ];
			$items[$i]['acl'] = $this->aa->getAcl( $item['post']['oid'] );
		}
		return $items;
	}

	private function validUserOID( $user_oid ) {
		$object = $this->rh->ctx->store->getObject($user_oid);

		if ( isset($object->type) && 'fuser' == $object->type ) {
			return true;
		} else {
			return false;
		}
	}

	private function showCommunityFeed() {
		$this->rh->useClass("Action_Community_ShowFeed");
		$sf = new Action_Community_ShowFeed( $this->module, array() );
		$sf->init();
		$sf->process();
	}

	public function process ()
	{
		$aa = &$this->aa;

		$aa->checkDeletions( array($this, "shutdown") );

		if ( !isset($this->params['user_url']) || empty($this->params['user_url'])
			|| !$this->validUserOID($this->params['user_url']) ) {
			$this->showCommunityFeed();
			return;
		}

		if ( !isset($aa->template_data['community']) ) {
			foreach ( $this->params as $key=>$val ) {
				if ( preg_match( '/^c(\d+)tdi(\d+)$/', $key, $matches ) ) {
					$this->model->pushTdiPerCommunity($matches[1], $matches[2]);
				}
			}
		}

		$this->model->doStuff();

		$forFreeMember = false;
		if ( isset($aa->acl_data['community_url']) && !empty($aa->acl_data['community_url']) ) {
			$view = $this->rh->views->findByName('member');
		} else {
			$view = $this->rh->views->findByName('onemember');
			$forFreeMember = true;
		}

		$view->data = $aa->template_data;

		if ( isset($aa->template_data['community']) ) {
			$tdis = $this->model->getTdiForFeed();
		} else {
			$tdi_selected = $this->model->getTdiPerCommunity();
			if ( !empty($tdi_selected) ) {
				foreach ( $tdi_selected as $key=>$val ) {
					$tdi_selected[$key] = array_flip($tdi_selected[$key]);
				}
			}

			$tdis_forfeed = $this->model->getTdiForFeedPerCommunity();

			$tdis = array();
			foreach ( $tdis_forfeed as $tdi ) {
				if ( $tdi['section'] > 0 ) {
					$object = $this->rh->ctx->store->getObject( $tdi['section'] );

					if ( $object instanceof fobject ) {
						$tdi['item'] = $object->data;
					}
				}
				$tdis[$tdi['community_oid']]['items'][] = $tdi;
				$tdis[$tdi['community_oid']]['count'] += $tdi['count'];
			}

			foreach ( $tdis as $key=>$val ) {
				$object = $this->rh->ctx->store->getObject( $key );

				if ( $object instanceof fobject ) {
					$tdis[$key]['community'] = $object->data;
				}
			}

			if ( !empty($tdi_selected) ) {
				foreach ( $tdis as $key=>$val ) {
					$countChecked = count($tdis[$key]['items']);
					foreach ( $tdis[$key]['items'] as $ikey=>$ival ) {
						if ( !isset($tdi_selected[$key][$ival['section']]) ) {
							$tdis[$key]['items'][$ikey]['unchecked'] = true;
							$countChecked--;
						}
					}
					if ( 0 == $countChecked ) {
						$tdis[$key]['unchecked'] = true;
					}
				}
				//print '<pre style="text-align:left;">'; print_r($tdis);exit;
			}

			$view->data['tdis'] = $tdis;
		}

		$view->data['can_create'] = $aa->is_granted(array('item_create', 'item_create_premod'));

		$items = $this->model->getItems();

		/**
		 * если какой юзер правил топик, надо подтянуть его данные
		 */
		foreach ( $items as $key=>$val ) {
			if ( isset($val['post']['edited_user_oid']) && !empty($val['post']['edited_user_oid']) ) {
				$object = $this->ctx->store->getObject($val['post']['edited_user_oid']);
				$items[$key]['post']['edited_user'] = $object->data;
			}
		}

		if ($items) {
			if ( $forFreeMember ) {
				foreach ( $items as $key=>$val ) {
					$items[$key]['post']['community_url'] = $aa->store->getObject($val['post']['community_oid'])->data['community_url'];
				}
			}

			$view->data['items'] = $this->processItems($items);
		} else {
			$view->data['message'] = "В этой ленте нет сообщений.";
		}

		// данные для постраничной листалки
		$pager = $this->getPagerInfo();
		$view->data['page'] = $pager;
		$view->data['items_remaining'] = $pager['items_remaining'];

		// -- sections -- {{{
		if ( isset($this->params['tdi_url']) ) {
			$view->data['defaultsection'] = $this->params['tdi_url'];
			$view->data['tdi_url'] = $this->params['tdi_url'];
			$view->data['tdi'] = $this->tdi_types[ $this->aa->acl_data['tdi_oid'] ];
			$view->data['tdi_title'] = $this->tdi_types[ $this->aa->acl_data['tdi_oid'] ]['title'];
			$view->data['tdi_color'] = $this->tdi_types[ $this->aa->acl_data['tdi_oid'] ]['color'];
		}

		$tag = $this->getParam('tag'); // instanceof fobject

		if ($tag) {
			$view->data['current_tag'] = $tag->data;
			$view->data['tag'] = $tag;
		}
		$view->data['tag_sections']['single'] = count($tdis) == 1 || isset($this->params['tdi_url']);
		// --- sections --- }}}

		$view->data['__widgets__'] = $this->widgets;

		// генерация урл адресов
		$this->rh->UseClass("RL_URLGenerator");
		$ug = new RL_URLGenerator($this->rh->router->getLastMatched()); //$this->rh->router->getRule('object_undelete')
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);

		// урл для постраничной листалки без ajax
		if (isset($pager['prev'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['prev'])));
			$view->data["prev_url"] = $ug->generateUrl();
		}

		if (isset($pager['next'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['next'])));
			$view->data["next_url"] = $ug->generateUrl();
		}

		unset($ug);

		// для постраничной листалки ajax handler
		if ($forFreeMember) {
			$ug = new RL_URLGenerator($this->rh->router->getRule('showfreemember_ajax'));
		} else {
			$ug = new RL_URLGenerator($this->rh->router->getRule('showmember_ajax'));
		}

		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);
		$ug->setGet($this->rh->GET);

		$view->data['ajax_url'] = $ug->generateUrl();

		// ShowMember specific variables
		$view->data['action_member_edit'] = $this->aa->acl_data['user_id'] == $this->getParam('user_oid');
		$view->data['member'] = $this->getParam('user')->data;
		$view->data['member']['oid'] = $this->getParam('user_oid');
		$view->data['member']['url'] = $this->getParam('user_oid');

		// -- грузим персон для юзера -- {{{
		$user = $this->getParam('user');
		$personDataList = array();
		if ($persons = $this->m_user->getPersons($user)) {
			foreach ($persons as $k=>$p) {
				$personDataList[$k] = $p->data;
			}
		}
		$view->data['member']['persons'] = $personDataList;
		// -- грузим персон для юзера -- }}}

		$this->rh->response->setContent( $view );

		// -- touch visitor stat -- {{{
		// visit member
		$this->ctx->mm->getModel("Visitable", "m")->getVisitable('Person')->setWhat($this->getParam('user_oid'))->visit();
		//
		// -- touch visitor stat -- }}}

	} // end of function process

	public function hrefFilterByTag ($tag)
	{
		$rule = 'showmember';

		$ug = new RL_URLGenerator($this->rh->router->getRule($rule));
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);
		$GET = $this->rh->GET;
		unset($GET[$this->rq_tag]);
		if ($tag === 'all') {
			$ug->setGet($GET);
		} else {
			$ug->setGet(array_merge($GET, array($this->rq_tag=>$tag)));
		}
		return $ug->generateUrl();
	} // end of method hrefFilterByDoctype

}
